package org.zhuzx.util;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 公用的并发执行器，内含动态线程池与任务队列，任务提交后由执行器统一分派线程运行。
 * @author zhuzx 2019年02月28日
 */
public class ConcurrentExecutor {
	
	private static ThreadPoolExecutor executor;
	static {
		int size = (HardwareVariables.CPU_THREAD_NUM + 1) * 2;
		BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(size);
		RejectedExecutionHandler handler = new AbstractConsumerQueue.BlockingPusher();
		executor = new ThreadPoolExecutor(1, HardwareVariables.CPU_THREAD_NUM, 30,
					TimeUnit.MINUTES, workQueue, handler);
		executor.prestartAllCoreThreads();
	}
	
	/**
	 * 提交一个任务，若任务队列已满则阻塞。
	 */
	public static void put(Runnable command) {
		executor.execute(command);
	}
	
	/**
	 * 关闭执行器并停止所有任务
	 */
	public static void shutdownNow() {
		executor.shutdownNow();
	}
	
}